<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="结算单编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入结算单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户企业" prop="companyId">
        <el-select v-model="queryParams.companyId" placeholder="请选择客户企业" clearable filterable>
          <el-option
            v-for="item in allCompanyList"
            :key="item.id"
            :label="item.nameSecond"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="签约主体" prop="signMainId">
        <el-select v-model="queryParams.signMainId" placeholder="请选择签约主体公司" clearable filterable>
          <el-option
            v-for="item in allSignMainList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="管理费税金类型" prop="taxType">
        <el-select
          v-model="queryParams.taxType"
          placeholder="请选择管理费税金类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.tax_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="税点(%)" prop="tax">
        <el-input
          v-model="queryParams.tax"
          placeholder="请输入税点,例如：6.75"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务费(元)" prop="serverAmount">
        <el-input
          v-model="queryParams.serverAmount"
          placeholder="请输入服务费"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务费周期" prop="serverAmountCycle">
        <el-date-picker clearable
                        v-model="queryParams.serverAmountCycle"
                        type="month"
                        value-format="yyyy-MM"
                        placeholder="请选择服务费周期">
        </el-date-picker>
      </el-form-item>
      <!--      <el-form-item label="工资" prop="salary">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.salary"-->
      <!--          placeholder="请输入工资"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="工资周期" prop="salaryCycle">-->
      <!--        <el-date-picker clearable-->
      <!--                        v-model="queryParams.salaryCycle"-->
      <!--                        type="month"-->
      <!--                        value-format="yyyy-MM"-->
      <!--                        placeholder="请选择工资周期">-->
      <!--        </el-date-picker>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="社保费" prop="socialSecurityAmount">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.socialSecurityAmount"-->
      <!--          placeholder="请输入社保费"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="社保费周期" prop="socialSecurityAmountCycle">-->
      <!--        <el-date-picker clearable-->
      <!--                        v-model="queryParams.socialSecurityAmountCycle"-->
      <!--                        type="month"-->
      <!--                        value-format="yyyy-MM"-->
      <!--                        placeholder="请选择社保费周期">-->
      <!--        </el-date-picker>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="公积金费" prop="accFundAmount">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.accFundAmount"-->
      <!--          placeholder="请输入公积金费"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="公积金费周期" prop="accFundAmountCycle">-->
      <!--        <el-date-picker clearable-->
      <!--                        v-model="queryParams.accFundAmountCycle"-->
      <!--                        type="month"-->
      <!--                        value-format="yyyy-MM"-->
      <!--                        placeholder="请选择公积金费周期">-->
      <!--        </el-date-picker>-->
      <!--      </el-form-item>-->

      <!--      <el-form-item label="开票时间" prop="invoicingTime">-->
      <!--        <el-date-picker clearable-->
      <!--                        v-model="queryParams.invoicingTime"-->
      <!--                        type="date"-->
      <!--                        value-format="yyyy-MM-dd"-->
      <!--                        placeholder="请选择开票时间">-->
      <!--        </el-date-picker>-->
      <!--      </el-form-item>-->
      <el-form-item label="开票状态" prop="invoicingStatus">
        <el-select
          v-model="queryParams.invoicingStatus"
          placeholder="请选择开票状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.invoicing_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="纳税方式" prop="invoiceType">
        <el-select
          v-model="queryParams.invoiceType"
          placeholder="请选择纳税方式"
          clearable
        >
          <el-option
            v-for="dict in dict.type.invoice_amount_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="回款金额" prop="returnAmount">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.returnAmount"-->
      <!--          placeholder="请输入回款金额"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="应收总计(元)" prop="shouldTotalAmount">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.shouldTotalAmount"-->
      <!--          placeholder="请输入应收总计金额"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="未收金额(元)" prop="notRcvAmount">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.notRcvAmount"-->
      <!--          placeholder="请输入未收金额"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="完成状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择完成状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.complete_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="结算单周期" prop="cycle">
        <el-date-picker clearable
                        v-model="queryParams.cycle"
                        type="month"
                        value-format="yyyy-MM"
                        placeholder="请选择结算单周期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['statement:statement:add']"-->
<!--        >新增-->
<!--        </el-button>-->
<!--      </el-col>-->
      <!--      <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['statement:statement:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['statement:statement:remove']"
              >删除</el-button>
            </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['statement:statement:export']"
        >导出
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleEditInvoicingStatus"-->
<!--          v-hasPermi="['statement:statement:export']"-->
<!--        >修改开票状态-->
<!--        </el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="statementList" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" align="center" width="50" fixed="left"/>
      <el-table-column label="结算单周期" align="center" prop="cycle" width="90"  fixed="left"/>
      <el-table-column label="结算单编号" align="center" prop="code" width="120" fixed="left"/>
      <el-table-column label="客户企业(二级)" align="center" prop="company.nameSecond" width="80" fixed="left"/>
      <el-table-column label="签约主体" align="center" prop="signMain.name"/>
      <el-table-column label="已回款金额(元)" align="center" prop="returnAmount" width="110"/>
      <el-table-column label="应收总计(元)" align="center" prop="shouldTotalAmount" width="110"/>
      <el-table-column label="未收金额(元)" align="center" prop="notRcvAmount" width="110"/>
      <el-table-column label="投保人数" align="center" prop="insureRenShu" />
      <el-table-column label="服务费(元)" align="center" prop="serverAmount" width="90"/>
      <el-table-column label="服务费周期" align="center" prop="serverAmountCycle" width="90"/>
      <el-table-column label="工资(元)" align="center" prop="salary"/>
      <el-table-column label="工资周期" align="center" prop="salaryCycle"/>
      <el-table-column label="社保费(元)" align="center" prop="socialSecurityAmount" width="90"/>
      <el-table-column label="社保费周期" align="center" prop="socialSecurityAmountCycle" width="90"/>
      <el-table-column label="公积金费(元)" align="center" prop="accFundAmount" width="110"/>
      <el-table-column label="公积金费周期" align="center" prop="accFundAmountCycle" width="100"/>
      <el-table-column label="服务费单价" align="center" prop="companyAgreement.serverMoney" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.companyAgreement.chargeUnitCategory === '1'">按岗位类别收取</span>
          <span v-if="scope.row.companyAgreement.chargeUnitCategory === '2'">自定义公式收取</span>
          <span v-if="scope.row.companyAgreement.chargeUnitCategory === '3'">{{scope.row.companyAgreement.serverMoney}}/人/月</span>
        </template>
      </el-table-column>
      <el-table-column label="管理费税金类型" align="center" prop="companyAgreement.taxType"   width="190">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tax_type" :value="scope.row.companyAgreement.taxType"/>
        </template>
      </el-table-column>
      <el-table-column label="税点(%)" align="center" prop="companyAgreement.tax"/>
      <!--      <el-table-column label="开票时间" align="center" prop="invoicingTime">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.invoicingTime, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column prop="invoicingStatus" label="开票状态" align="center" width="150" >
        <template slot-scope="scope">
<!--          <dict-tag :options="dict.type.invoicing_status" :value="scope.row.invoicingStatus"/>-->
          <el-select
            v-model="scope.row.invoicingStatus"
            placeholder="请选择开票状态"
            size="small"
            style="width:110px"
            @change="changeInvoicingStatus(scope.row.id,scope.row.invoicingStatus)"
          >
            <el-option
              v-for="dict in dict.type.invoicing_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </template>

      </el-table-column>
      <el-table-column prop="companyAgreement.invoiceType" label="纳税方式" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.invoice_amount_type" :value="scope.row.companyAgreement.invoiceType"/>
        </template>
      </el-table-column>
      <el-table-column label="修改金额原因" align="center" prop="editAmountReason" width="200" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          <span>{{scope.row.editAmountReason}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="完成状态" align="center" fixed="right">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.complete_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作A" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="showDetail(scope.row)"
            v-hasPermi="['statement:statement:showTouBaoDetail']"
          >查看投保明细
          </el-button>
          <el-button
            v-hasPermi="['statement:statement:addSheGong']"
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="addSsafWage(scope.row)"
          >添加工资社公
          </el-button>
          <el-button
            v-hasPermi="['statement:statement:addGongZiDetail']"
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="addSsafDetail(scope.row)"
          >添加工资明细
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="editTotalAmount(scope.row)"
            v-hasPermi="['statement:statement:editTotalAmount']"
          >修改应收总计
          </el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="handleUpdate(scope.row)"-->
          <!--            v-hasPermi="['statement:statement:edit']"-->
          <!--          >修改</el-button>-->
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['statement:statement:remove']"-->
          <!--          >删除</el-button>-->
        </template>
      </el-table-column>
      <el-table-column label="操作B" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-plus"
            @click="addReturnRecord(scope.row)"
            v-hasPermi="['statementReturnRecord:statementReturnRecord:add']"
          >创建回款
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="viewReturnRecord(scope.row)"
            v-hasPermi="['statementReturnRecord:statementReturnRecord:list']"
          >查看回款记录
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-plus"
            @click="addInvoice(scope.row)"
            v-hasPermi="['statementInvoice:statementInvoice:add']"
          >录入发票
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="viewInvoice(scope.row)"
            v-hasPermi="['statementInvoice:statementInvoice:list']"
          >查看发票记录
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改结算单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="结算单周期" prop="cycle" v-if="disable === false">
          <el-date-picker clearable
                          v-model="form.cycle"
                          type="month"
                          value-format="yyyy-MM"
                          placeholder="请选择结算单周期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户企业(二级)" prop="companyId" v-if="disable === false">
          <el-input v-model="form.companyId" placeholder="请输入客户企业"/>
        </el-form-item>
        <el-form-item label="签约主体公司" prop="signMainId" v-if="disable === false">
          <el-input v-model="form.signMainId" placeholder="请输入签约主体公司"/>
        </el-form-item>
        <el-form-item label="客户合同" prop="companyAgreementId" v-if="disable === false">
          <el-input v-model="form.companyAgreementId" placeholder="请输入客户合同"/>
        </el-form-item>
        <el-form-item label="服务费(元)" prop="serverAmount" v-if="disable === false">
          <el-input v-model="form.serverAmount" placeholder="请输入服务费"/>
        </el-form-item>
        <el-form-item label="服务费周期" prop="serverAmountCycle" v-if="disable === false">
          <el-date-picker clearable
                          v-model="form.serverAmountCycle"
                          type="month"
                          value-format="yyyy-MM"
                          placeholder="请选择服务费周期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="工资(元)" prop="salary" >
          <el-input v-model="form.salary" placeholder="请输入工资，不能为负，且最多保留两位小数"
                    style="width: 400px"
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    maxlength="20"
                    show-word-limit />
        </el-form-item>
        <div style="margin-bottom: 25px;margin-left: 50px;color:red;font-size: 14px">
          提示：若已导入工资明细，此工资为明细之和；修改工资数须重新导入明细表！
        </div>
        <el-form-item label="工资周期" prop="salaryCycle"  >
          <el-date-picker clearable
                          style="width: 400px"
                          v-model="form.salaryCycle"
                          type="month"
                          value-format="yyyy-MM"
                          placeholder="请选择工资周期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="社保费(元)" prop="socialSecurityAmount"  >
          <el-input v-model="form.socialSecurityAmount" placeholder="请输入社保费，不能为负，且最多保留两位小数"
                    style="width: 400px"
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    maxlength="20"
                    show-word-limit />
        </el-form-item>
        <el-form-item label="社保费周期" prop="socialSecurityAmountCycle"  >
          <el-date-picker clearable
                          style="width: 400px"
                          v-model="form.socialSecurityAmountCycle"
                          type="month"
                          value-format="yyyy-MM"
                          placeholder="请选择社保费周期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="公积金费(元)" prop="accFundAmount" >
          <el-input v-model="form.accFundAmount" placeholder="请输入公积金费，不能为负，且最多保留两位小数"
                    style="width: 400px"
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    maxlength="20"
                    show-word-limit />
        </el-form-item>
        <el-form-item label="公积金费周期" prop="accFundAmountCycle" >
          <el-date-picker clearable
                          style="width: 400px"
                          v-model="form.accFundAmountCycle"
                          type="month"
                          value-format="yyyy-MM"
                          placeholder="请选择公积金费周期">
          </el-date-picker>
        </el-form-item>
        <!--        <el-form-item label="税点(%)" prop="tax">-->
        <!--          <el-input v-model="form.tax" placeholder="请输入税点，例如：6.72" />-->
        <!--        </el-form-item>-->
        <el-form-item label="开票时间" prop="invoicingTime" v-if="disable === false">
          <el-date-picker clearable
                          v-model="form.invoicingTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择开票时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="已回款金额" prop="returnAmount" v-if="disable === false">
          <el-input v-model="form.returnAmount" placeholder="请输入已回款金额"/>
        </el-form-item>
        <el-form-item label="应收总计金额" prop="shouldTotalAmount" v-if="disable === false">
          <el-input v-model="form.shouldTotalAmount" placeholder="请输入应收总计金额"/>
        </el-form-item>
        <el-form-item label="未收金额" prop="notRcvAmount" v-if="disable === false">
          <el-input v-model="form.notRcvAmount" placeholder="请输入未收金额"/>
        </el-form-item>
<!--        <el-form-item label="备注" prop="remark">-->
<!--          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>-->
<!--        </el-form-item>-->
      </el-form>

      <el-upload class="upload-demo"
                 ref="uploadFile"
                 :headers="uploadFile.headers"
                 :action="uploadFile.url"
                 :on-success="handleAvatarSuccess"
                 :show-file-list="false">
        <el-button slot="trigger" size="small" type="primary">上传文件</el-button>
      </el-upload>

      <el-table class="down" :data="ssafWageFileList" border stripe style="width: 100%;margin-top: 20px;">
        <el-table-column prop="fileName" label="文件名称"></el-table-column>
<!--        <el-table-column prop="attachSize" label="文件大小">-->
<!--          <template slot-scope="scope">-->
<!--            <span v-if="scope.row.attachSize / 1024 / 1024 < 1">{{(scope.row.attachSize / 1024).toFixed(2) + 'KB'}}</span>-->
<!--            <span v-else>{{(scope.row.attachSize / 1024 / 1024).toFixed(2) + 'MB'}}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column prop="createTime" label="上传时间"></el-table-column>
        <el-table-column width="150px" label="操作">
          <template slot-scope="scope">
            <el-button size="small" type="text">
              <a @click="downloadFile(scope.row.fileName,scope.row.fileUrl)">下载</a>
            </el-button>
            <el-button size="small" type="text" @click="deleteFile(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="querySsafWageFile.total>0"
        :total="querySsafWageFile.total"
        :page.sync="querySsafWageFile.pageNum"
        :limit.sync="querySsafWageFile.pageSize"
        @pagination="getSsafWageFileList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改应收总计金额对话框 -->
    <el-dialog :title="editTotalAmountDialog.title" :visible.sync="editTotalAmountDialog.open" width="800px" append-to-body>
      <el-form ref="editTotalAmountForm" :model="editTotalAmountForm" :rules="editTotalAmountDialog.rules" label-width="120px">
        <el-form-item label="旧应收总计金额" prop="shouldTotalAmount" >
          <el-input v-model="editTotalAmountForm.shouldTotalAmount" placeholder="请输入旧应收总计金额" :disabled="true" style="width: 500px"/>
        </el-form-item>
        <el-form-item label="新应收总计金额" prop="shouldTotalAmountNew" >
          <el-input v-model="editTotalAmountForm.shouldTotalAmountNew" style="width: 500px" placeholder="请输入新应收总计金额，不能为负数，且保留两位小数" oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    maxlength="20"
                    show-word-limit />
        </el-form-item>
        <el-form-item label="旧修改原因" prop="editAmountReason" v-if="false">
          <el-input v-model="editTotalAmountForm.editAmountReason" type="textarea" placeholder="请输入修改原因"/>
        </el-form-item>
        <el-form-item label="修改原因" prop="editAmountReasonNew">
          <el-input v-model="editTotalAmountForm.editAmountReasonNew" type="textarea" placeholder="请输入修改原因" :autosize="{ minRows: 4, maxRows: 9}"  maxlength="100" show-word-limit/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditTotalAmountForm">确 定</el-button>
        <el-button @click="cancelEditTotalAmountForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加结算单回款记录对话框 -->
    <el-dialog :title="returnDialog.title" :visible.sync="returnDialog.open" width="700px" append-to-body>
      <el-form ref="returnForm" :model="returnForm" :rules="returnDialog.rules" label-width="120px">
        <!--        <el-form-item label="发票编号" prop="invoiceCode">-->
        <!--          <el-input v-model="returnForm.invoiceId" placeholder="发票编号"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="回款金额(元)" prop="returnAmount">
          <el-input v-model="returnForm.returnAmount" placeholder="请输入回款金额" style="width: 360px"
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    maxlength="20"
                    show-word-limit/>
        </el-form-item>
        <el-form-item label="回款时间" prop="returnTime">
          <el-date-picker clearable
                          v-model="returnForm.returnTime"
                          type="datetime"
                          style="width: 360px"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择回款时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发票号码" prop="invoiceCode" >
          <el-input v-model="returnForm.invoiceId" placeholder="发票号码"  maxlength="30" show-word-limit  style="width: 360px" />
        </el-form-item>
        <el-form-item label="登记人员" prop="createBy">
          <el-input v-model="returnForm.createBy" placeholder="请输入登记人员" style="width: 360px"  maxlength="30" show-word-limit  />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="returnForm.remark" type="textarea" placeholder="请输入内容" maxlength="255" show-word-limit/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="returnSubmitForm">确 定</el-button>
        <el-button @click="returnCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加结算单发票记录对话框 -->
    <el-dialog :title="invoiceDialog.title" :visible.sync="invoiceDialog.open" width="700px" append-to-body>
      <el-form ref="invoiceForm" :model="invoiceForm" :rules="invoiceDialog.rules" label-width="120px">
        <el-form-item label="主要商品名称" prop="productName">
          <el-input v-model="invoiceForm.productName" style="width: 400px" placeholder="请输入主要商品名称" maxlength="40"
                    show-word-limit/>
        </el-form-item>
        <el-form-item label="客户识别号" prop="companyNum">
          <el-input v-model="invoiceForm.companyNum" style="width: 400px" placeholder="请输入客户识别号" maxlength="60"
                    show-word-limit/>
        </el-form-item>
        <el-form-item label="发票代码" prop="code">
          <el-input v-model="invoiceForm.code" style="width: 400px" placeholder="请输入发票代码" maxlength="60"
                    show-word-limit/>
        </el-form-item>
        <el-form-item label="发票号码" prop="number">
          <el-input v-model="invoiceForm.number" style="width: 400px" placeholder="请输入发票号码" maxlength="60"
                    show-word-limit/>
        </el-form-item>
        <el-form-item label="开票人" prop="drawer">
          <el-input v-model="invoiceForm.drawer" style="width: 400px" placeholder="请输入开票人"
                    maxlength="40"
                    show-word-limit/>
        </el-form-item>
        <el-form-item label="合计金额" prop="totalAmount">
          <el-input v-model="invoiceForm.totalAmount" style="width: 400px" placeholder="请输入合计金额"
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    maxlength="20"
                    show-word-limit
                    @change="addToTotalPriceTax"
          />
        </el-form-item>
        <el-form-item label="税额" prop="taxAmount">
          <el-input v-model="invoiceForm.taxAmount" style="width: 400px" placeholder="请输入税额"
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    maxlength="20"
                    show-word-limit
                    @change="addToTotalPriceTax"
          />
        </el-form-item>
        <el-form-item label="价税合计" prop="totalPriceTax">
          <el-input v-model="invoiceForm.totalPriceTax" style="width: 400px" placeholder="请输入价税合计"
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    maxlength="20"
                    show-word-limit/>
        </el-form-item>
        <el-form-item label="发票类型" prop="type">
          <el-select
            v-model="invoiceForm.type"
            placeholder="请选择发票类型"
            clearable
            style="width: 400px"
          >
            <el-option
              v-for="dict in dict.type.import_invoice_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发票状态" prop="status">
          <el-select
            v-model="invoiceForm.status"
            placeholder="请选择发票状态"
            clearable
            style="width: 400px"
          >
            <el-option
              v-for="dict in dict.type.import_invoice_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="开票时间" prop="invoicingTime">
          <el-date-picker clearable
                          style="width: 400px"
                          v-model="invoiceForm.invoicingTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择开票时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="invoiceForm.remark" type="textarea" placeholder="请输入内容" maxlength="255" show-word-limit/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="invoiceSubmitForm">确 定</el-button>
        <el-button @click="invoiceCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStatement,
  getStatement,
  delStatement,
  addStatement,
  updateStatement,
  editTotalAmount, addSsafWage
} from "@/api/statement/statement";
import {listAllSignMain} from "@/api/sign_main/signmain";
import {listAllCompany} from "@/api/company/company";
import {addStatementReturnRecord} from "@/api/statement_return_record/statementreturnrecord";
import {addStatementInvoice} from "@/api/statement_invoice/statementinvoice";
import { getUserProfile } from "@/api/system/user";
import {getToken} from "@/utils/auth";
import {uploadImgBatch} from "@/api/common";
import {
  addStatementSsafWage,
  delStatementSsafWage,
  listStatementSsafWage
} from "@/api/statement_ssaf_wage/statementssafwage";
export default {
  name: "Statement",
  dicts: ['invoicing_status', 'invoice_amount_type', 'tax_type', 'complete_status', 'import_invoice_type', 'import_invoice_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 结算单表格数据
      statementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //禁用flag
      disable: false,
      // 查询参数
      queryParams: {
        orderByColumn:'m.create_time',
        isAsc:'desc',
        code: null,
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        signMainId: null,
        companyAgreementId: null,
        serverAmount: null,
        serverAmountCycle: null,
        salary: null,
        salaryCycle: null,
        socialSecurityAmount: null,
        socialSecurityAmountCycle: null,
        accFundAmount: null,
        accFundAmountCycle: null,
        taxType: null,
        tax: null,
        invoicingTime: null,
        invoicingStatus: null,
        invoiceType: null,
        returnAmount: null,
        shouldTotalAmount: null,
        notRcvAmount: null,
        status: null,
        cycle: null,
        ids:[],
      },
      // 表单参数
      form: {

      },
      // 表单校验
      rules: {
      },
      // 签约主体公司
      allSignMainList: [],
      allCompanyList: [],

      //回款弹框
      returnDialog: {
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        rules: {
          returnTime: [{required: true, trigger: 'blur', message: '请选择回款时间'}],
          returnAmount: [{required: true, trigger: 'blur', message: '请输入回款金额'}],
        },
      },
      //回款表单
      returnForm: {},

      //发票弹框
      invoiceDialog: {
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        rules: {
          productName: [{required: true, trigger: 'blur', message: '请选择主要商品名称'}],
          companyNum: [{required: true, trigger: 'blur', message: '请输入客户识别号'}],
          code: [{required: true, trigger: 'blur', message: '请输入发票代码'}],
          number: [{required: true, trigger: 'blur', message: '请输入发票号码'}],
          drawer: [{required: true, trigger: 'blur', message: '请输入发票人'}],
          totalAmount: [{required: true, trigger: 'blur', message: '请输入合计金额'}],
          taxAmount: [{required: true, trigger: 'blur', message: '请输入税额'}],
          totalPriceTax: [{required: true, trigger: 'blur', message: '请输入价税合计'}],
          type: [{required: true, trigger: 'blur', message: '请输入发票类型'}],
          status: [{required: true, trigger: 'blur', message: '请输入发票状态'}],
          invoicingTime: [{required: true, trigger: 'blur', message: '请输入开票时间'}],
        },
      },
      //当前用户信息
      user: {},
      //发票表单
      invoiceForm: {},
      //修改金额表单
      editTotalAmountForm:{},
      //修改金额对话框
      editTotalAmountDialog:{
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        rules: {
          shouldTotalAmountNew: [{required: true, trigger: 'blur', message: '请输入新应收总计金额'}],
          editAmountReasonNew: [{required: true, trigger: 'blur', message: '请输入修改原因'}],
        },
      },
      // 上传附件参数
      uploadFile: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      //工资社公附件list
      ssafWageFileList:[],
      //添加工资社公附件表单
      addSsafWageForm: {
        fileUrl:null,
        fileName:null,
        statementId:null,
      },
      //查询工资社公附件参数
      querySsafWageFile:{
        pageNum: 1,
        pageSize: 5,
        total:0,
        loading: true,
      },

    };
  },
  created() {
    this.getList();
    this.getSignMainList();
    this.getCompanyList();
    this.getUser();
  },
  methods: {
    /** 查询结算单列表 */
    getList() {
      this.loading = true;
      listStatement(this.queryParams).then(response => {
        this.statementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      //表单重置
      this.addSsafWageForm.fileUrl = null;
      this.addSsafWageForm.fileName = null;
      this.addSsafWageForm.statementId = null;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        companyId: null,
        signMainId: null,
        companyAgreementId: null,
        serverAmount: null,
        serverAmountCycle: null,
        salary: null,
        salaryCycle: null,
        socialSecurityAmount: null,
        socialSecurityAmountCycle: null,
        accFundAmount: null,
        accFundAmountCycle: null,
        taxType: null,
        tax: null,
        invoicingTime: null,
        invoicingStatus: null,
        invoiceType: null,
        returnAmount: null,
        shouldTotalAmount: null,
        notRcvAmount: null,
        status: null,
        cycle: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    // handleAdd() {
    //   this.reset();
    //   this.open = true;
    //   this.disable = false;
    //   this.title = "添加结算单";
    // },
    /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.reset();
    //   this.disable = false;
    //   const id = row.id || this.ids
    //   getStatement(id).then(response => {
    //     this.form = response.data;
    //     this.open = true;
    //     this.title = "修改结算单";
    //   });
    // },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            addSsafWage(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              //表单重置
              this.addSsafWageForm.fileUrl = null;
              this.addSsafWageForm.fileName = null;
              this.addSsafWageForm.statementId = null;
            });
          }
          // else {
          //   addStatement(this.form).then(response => {
          //     this.$modal.msgSuccess("新增成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // }
        }
      });
    },
    /** 删除按钮操作 */
    // handleDelete(row) {
    //   const ids = row.id || this.ids;
    //   this.$modal.confirm('是否确认删除结算单编号为"' + ids + '"的数据项？').then(function () {
    //     return delStatement(ids);
    //   }).then(() => {
    //     this.getList();
    //     this.$modal.msgSuccess("删除成功");
    //   }).catch(() => {
    //   });
    // },
    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.ids = this.ids;
      this.download('statement/statement/export', {
        ...this.queryParams
      }, `statement_${new Date().getTime()}.xlsx`)
    },
    // 获取签约主体列表
    getSignMainList() {
      let q = {};
      listAllSignMain(q).then(response => {
        this.allSignMainList = response;
      });
    },
    // 获取客户企业列表
    getCompanyList() {
      let q = {};
      listAllCompany(q).then(response => {
        this.allCompanyList = response;
      });
    },

    //查看详情
    showDetail(row) {
      const id = row.id
      this.$router.push({path: '/center_settlement/statementdetail/', query: {id: id}})
    },
    //添加工资社公
    addSsafWage(row) {
      this.reset();
      this.disable = true;
      const id = row.id || this.ids
      getStatement(id).then(response => {
        this.form = response.data;
        this.addSsafWageForm.statementId = id;
        this.querySsafWageFile.statementId = id;
        this.getSsafWageFileList();
        this.open = true;
        this.title = "添加工资社公";
      });
    },
    //修改应收总计
    editTotalAmount(row){
      this.resetEditTotalAmount();
      this.editTotalAmountDialog.open = true;
      this.editTotalAmountDialog.title = "修改应收总计金额";
      this.editTotalAmountForm.id = row.id;
      this.editTotalAmountForm.shouldTotalAmount = row.shouldTotalAmount;
      this.editTotalAmountForm.editAmountReason = row.editAmountReason;
    },

    //查看回款记录
    viewReturnRecord(row) {
      const id = row.id
      this.$router.push({path: '/center_settlement/statementreturnrecord/', query: {id: id}})
    },
    //创建回款
    addReturnRecord(row) {
      this.resetReturn();
      this.returnDialog.title = "创建回款";
      this.returnForm.statementId = row.id;
      this.returnForm.companyId = row.companyId;
      this.returnForm.createBy = this.user.nickName;
      this.returnDialog.open = true;
    },
    //回款表单重置
    resetReturn() {
      this.returnForm = {
        id: null,
        statementId: null,
        companyId: null,
        invoiceId: null,
        returnAmount: null,
        returnTime: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        statementCode: null,
        companyNameSecond: null,
        invoiceCode: null,
      };
      this.resetForm("returnForm");
    },
    /** 回款提交按钮 */
    returnSubmitForm() {
      this.$refs["returnForm"].validate(valid => {
        if (valid) {
          addStatementReturnRecord(this.returnForm).then(response => {
            this.$modal.msgSuccess("创建回款成功");
            this.returnDialog.open = false;
            this.getList();
          });
        }
      });
    },
    /** 回款取消按钮 */
    returnCancel() {
      this.returnDialog.open = false;
      this.resetReturn();
    },

    //查看发票记录
    viewInvoice(row) {
      const id = row.id
      this.$router.push({path: '/center_settlement/statementinvoice/', query: {id: id}})
    },
    //录入发票
    addInvoice(row) {
      this.resetInvoice();
      this.invoiceDialog.open = true;
      this.invoiceDialog.title = "录入发票";
      this.invoiceForm.statementId = row.id;
      this.invoiceForm.companyId = row.companyId;
      this.invoiceForm.signMainId = row.signMainId;
    },
    //发票表单重置
    resetInvoice() {
      this.invoiceForm = {
        id: null,
        statementId: null,
        companyId: null,
        signMainId: null,
        productName: null,
        companyNum: null,
        code: null,
        companyName: null,
        type: null,
        number: null,
        drawer: null,
        totalAmount: null,
        taxAmount: null,
        totalPriceTax: null,
        status: null,
        invoicingTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("invoiceForm");
    },
    /** 发票提交按钮 */
    invoiceSubmitForm() {
      this.$refs["invoiceForm"].validate(valid => {
        if (valid) {
          addStatementInvoice(this.invoiceForm).then(response => {
            this.$modal.msgSuccess("录入发票成功");
            this.invoiceDialog.open = false;
            this.getList();
          });
        }
      });
    },
    /** 发票取消按钮 */
    invoiceCancel() {
      this.invoiceDialog.open = false;
      this.resetInvoice();
    },
    //修改金额表单重置
    resetEditTotalAmount() {
      this.editTotalAmountForm = {
        id: null,
        shouldTotalAmount:null,
        shouldTotalAmountNew:null,
        editAmountReason:null,
        editAmountReasonNew:null,
      };
      this.resetForm("editTotalAmountForm");
    },
    /** 修改金额提交*/
    submitEditTotalAmountForm(){
      this.$refs["editTotalAmountForm"].validate(valid => {
        if (valid) {
          editTotalAmount(this.editTotalAmountForm).then(response => {
            this.$modal.msgSuccess("修改金额成功");
            this.editTotalAmountDialog.open = false;
            this.getList();
          });
        }
      });
    },
    /** 修改金额取消 */
    cancelEditTotalAmountForm() {
      this.editTotalAmountDialog.open = false;
      this.resetEditTotalAmount();
    },
    /** 累加到 价税合计 */
    addToTotalPriceTax(value) {
      var totalPrice = 0.00;
      var taxAmount = 0.00;
      if (this.invoiceForm.totalAmount){
        totalPrice = parseFloat(this.invoiceForm.totalAmount)
      }
      if (this.invoiceForm.taxAmount){
        taxAmount = parseFloat(this.invoiceForm.taxAmount)
      }
      this.invoiceForm.totalPriceTax = Math.round((totalPrice + taxAmount) * 100)/100;
    },
    /** */
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
    /** 改变结算单 开票状态 */
    changeInvoicingStatus(id,val){
      if (val){
        updateStatement(Object({ id:id, invoicingStatus:val})).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      }
    },
    //上传成功
    handleAvatarSuccess(res, file, fileList) {
      // console.log(res)
      this.addSsafWageForm.fileUrl = res.url
      this.addSsafWageForm.fileName = res.originalFilename;
      this.submitAddSsafWageForm();
    },
    // 表单提交
    submitAddSsafWageForm() {
      addStatementSsafWage(this.addSsafWageForm).then(data => {
        this.$message.success('添加成功')
        this.getSsafWageFileList();
      })
    },
    //获取工资社公附件list
    getSsafWageFileList(){
      this.querySsafWageFile.loading = true;
      listStatementSsafWage(this.querySsafWageFile).then(response => {
        this.ssafWageFileList = response.rows;
        this.querySsafWageFile.total = response.total;
        this.querySsafWageFile.loading = false;
      })
    },
    //下载
    downloadFile(name,url){
      // var a = document.createElement('a');
      // var event = new MouseEvent('click');
      // a.download = name;
      // a.href = url;
      // a.dispatchEvent(event);
      this.downloadNew(url,name);
    },
    downloadNew(url,name) {
      var fileName = 'file.png'
      console.log(url)
      if(name){
        fileName = name
      }
      else if (url) {
        var index = url.lastIndexOf('/')
        var str = url.substring(index + 1, url.length)
        fileName = str
      }

      fetch(url).then(res => res.blob().then(blob => {
        var a = document.createElement('a')
        var url = window.URL.createObjectURL(blob)
        var filename = fileName
        a.href = url
        a.download = filename
        a.click()
        window.URL.revokeObjectURL(url)
      }))
    },

    //删除
    deleteFile(id){
      this.$confirm('是否确认删除该附件', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delStatementSsafWage(id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getSsafWageFileList()
      })

    },

    addSsafDetail(row){
      const id = row.id;
      const chargeUnitCategory = row.companyAgreement.chargeUnitCategory;
      this.$router.push({ path: '/center_settlement/Statementsalaryservermoney/', query: { statementId: id,chargeUnitCategory:chargeUnitCategory } })
    }

  }
};
</script>
